<template>
  <div class="chart-card">
    <!-- 顶部金额 -->
    <Amount
      :amount="showNum ? total_zichan : _hide(total_zichan)"
      @handleYanjin="handleYanjin"
      @handleShuaxin="handleShuaxin"
      :type="type"
      :showicon="showNum ? 'yanjin-k' : 'yanjin-g'"
      :showMoni="moni"
    />

    <div style="padding: 0 24px;">
      <!-- 图表 -->
      <div class="chart-container">
        <div class="line-chart-container">
          <div ref="chartRef" class="chart-box"></div>

          <!-- 加载中 -->
          <div v-if="loading" class="chart-loading">
            <van-loading size="24px" type="spinner" color="#17AC74">{{ t('loading') }}</van-loading>
          </div>

          <!-- 暂无数据 -->
          <div v-else-if="noData" class="chart-empty">
            <img src="/static/img/empty_data.png" class="chart-empty-img" alt="empty" />
            <div class="chart-empty-text">{{ t('no_data') }}</div>
          </div>
        </div>

        <!-- 切换按钮 -->
        <div class="chart-btn-group">
          <button :class="['chart-btn', daysType === 7 ? 'active' : '']" @click="switchDays(7)">
            7 {{ t('day') }}
          </button>
          <button :class="['chart-btn', daysType === 30 ? 'active' : '']" @click="switchDays(30)">
            30 {{ t('day') }}
          </button>
        </div>
      </div>

      <div style="height: 40px;"></div>

      <!-- 我的账户 -->
      <div class="account-title">{{ t('22_myaccount') }}</div>
      <div class="account-card">
        <div class="account-list">
          <!-- 总资产 -->
          <div class="account-item">
            <div class="account-icon-bg">
              <img :src="a2" class="account-icon" />
            </div>
            <div class="account-main">
              <div class="account-row">
                <div class="account-name">{{ t('22_totalassets') }}</div>
                <div class="account-value">
                  {{ total_zichan }}
                  <span class="account-percent">(100%)</span>
                </div>
              </div>
              <div class="account-progress-bar-bg">
                <div
                  class="account-progress-bar"
                  :style="{ width: parseFloat(total_per) ? total_per : '0%', background: '#ffb1b1' }"
                ></div>
              </div>
            </div>
          </div>

          <!-- 子账户资产 -->
          <template v-for="(item, idx) in accountList" :key="idx">
            <div class="account-item">
              <div class="account-icon-bg">
                <img :src="item.icon" class="account-icon" />
              </div>
              <div class="account-main">
                <div class="account-row">
                  <div class="account-name">{{ item.name }}</div>
                  <div class="account-value">
                    {{ item.value }}
                    <span class="account-percent">({{ item.percent }})</span>
                  </div>
                </div>
                <div class="account-progress-bar-bg">
                  <div
                    class="account-progress-bar"
                    :style="{ width: parseFloat(item.percent) ? item.percent : '0%', background: item.color }"
                  ></div>
                </div>
              </div>
            </div>
          </template>
        </div>
      </div>

      <div style="height: 100px;"></div>
    </div>
  </div>
</template>

<script setup>
import { _hide } from '@/utils/public.js'
import Amount from './amount.vue'
import { useI18n } from 'vue-i18n'
import { ref, computed, onMounted, onBeforeUnmount, nextTick } from 'vue'
import { useUserStore } from '@/store/user/index'
import * as echarts from 'echarts'
import { getRecent } from '@/api/user'
import dayjs from 'dayjs'
import { showToast } from 'vant'


// 图标
import a1 from '@/assets/defi/a1.png'
import a2 from '@/assets/defi/a2.png'
import a3 from '@/assets/defi/a3.png'
import a4 from '@/assets/defi/a4.png'
import a5 from '@/assets/defi/a5.png'
import a6 from '@/assets/defi/a6.png'

const props = defineProps({
  assetDetails: Object,
  amountSum: String,
  showNum: Boolean,
  type: String
})
const { t } = useI18n()
const emit = defineEmits(['handleYanjin', 'handleShuaxin'])
const handleYanjin = () => emit('handleYanjin')
const handleShuaxin = () => emit('handleShuaxin')

const moni = ref('show')
const total_zichan = ref(0.0)
const total_per = ref('100.0%')
const userStore = useUserStore()

// ====================== 账户配置 ======================
const typeConfig = {
  1: { name: t('22_platformassets'), icon: a1, color: '#3b5bfd' },
  2: { name: t('22_aiaccount'), icon: a2, color: '#7ad1e7' },
  3: { name: t('22_contractassets'), icon: a3, color: '#b18cff' },
  4: { name: t('22_quantcontract'), icon: a4, color: '#ffd86b' },
  5: { name: t('22_quantarb'), icon: a5, color: '#ffb1b1' },
  6: { name: t('22_optioncontract'), icon: '/static/img/J7Q_e549ee0d_1Po.faef1900.svg', color: '#b1c6ff' },
  7: { name: t('22_followcontract'), icon: a6, color: '#b1ffd6' },
  8: { name: t('22_aipredict'), icon: '/static/img/J7Q_e549ee0d_1Po.faef1900.svg', color: '#b2c6ff' },
  9: { name: t('22_spotassets'), icon: a6, color: '#b1f4d6' }
}

// ====================== 账户列表 ======================
const accountList = computed(() => {
  const assets = userStore.userInfo.asset || []

  // ① 过滤：只要 symbol=usdt 且排除某些类型（原逻辑保持）
  const filtered =
    assets
      .filter(
        (item) =>
          item.symbol === 'usdt' &&
          item.type != 2 &&
          item.type != 5 &&
          item.type != 6 &&
          item.type != 7 &&
          item.type != 8
      )
      .map((item) => {
        const cfg = typeConfig[item.type] || {}
        let value = Number(item.amout ?? 0)

        // ✅ 如果是现货资产 (type=9)，则加上所有 type=9 的 exchageAmount 合计
        if (item.type === 9) {
          const spotTotal = assets
            .filter((x) => x.type === 9)
            .reduce((sum, x) => sum + Number(x.exchageAmount ?? 0), 0)
          value = spotTotal
        }

        return {
          ...item,
          name: cfg.name || t('22_unknownasset'),
          icon: cfg.icon || '',
          color: cfg.color || '#ccc',
          value
        }
      }) || []

  // ② 计算总资产
  const total = filtered.reduce((sum, item) => sum + item.value, 0)
  total_zichan.value = total.toFixed(2)

  // ③ 计算百分比并排序
  return filtered
    .map((item) => ({
      ...item,
      value: Number(item.value).toFixed(2), // ✅ 保留 4 位小数
      percent: total > 0 ? `${((item.value / total) * 100).toFixed(2)}%` : '0.00%'
    }))
    .sort((a, b) => b.value - a.value)

})


// ====================== 折线图 ======================
const chartRef = ref(null)
let chartInstance = null
const daysType = ref(7)
const allBalanceHistory = ref([])
const loading = ref(true)
const noData = ref(false)

// 获取资金趋势
async function fetchAllBalance() {
  try {
    loading.value = true
    noData.value = false

    const res = await getRecent(daysType.value)
    if (res && Array.isArray(res.data)) {
      allBalanceHistory.value = res.data.map((item) => ({
        date: item.date || item.time || dayjs().format('YYYY-MM-DD'),
        balance: Number(item.balance ?? item.profit ?? 0)
      }))
    } else {
      allBalanceHistory.value = []
    }

    const allZero = allBalanceHistory.value.every((d) => d.balance === 0)
    noData.value = allZero || allBalanceHistory.value.length === 0

    nextTick(() => updateChart())
  } catch (e) {
    console.error('获取统计图数据失败:', e)
    showToast(t('network_error'))
    noData.value = true
  } finally {
    loading.value = false
  }
}

// 获取数据
function getFilteredData() {
  const data = allBalanceHistory.value || []
  return {
    xAxis: data.map((d) => dayjs(d.date).format('MM-DD')),
    series: data.map((d) => Number(d.balance))
  }
}

// 更新图表（余额趋势）
function updateChart() {
  if (!chartInstance) return
  const { xAxis, series } = getFilteredData()
  if (!series.length) return

  // 格式化函数（带 K / M / B）
  const formatVal = (val) => {
    if (val >= 1_000_000_000) return (val / 1_000_000_000).toFixed(2) + 'B'
    if (val >= 1_000_000) return (val / 1_000_000).toFixed(2) + 'M'
    if (val >= 1_000) return (val / 1_000).toFixed(2) + 'K'
    return val.toFixed(2)
  }

  const maxVal = Math.max(...series)
  const minVal = Math.min(...series)

  // ✅ 增加上下边距，让曲线更高、更明显
  const yPadding = (maxVal - minVal) * 0.2 || maxVal * 0.2
  const yMin = Math.max(minVal - yPadding, 0)
  const yMax = maxVal + yPadding

  chartInstance.setOption({
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(0,0,0,0.7)',
      textStyle: { color: '#fff' },
      formatter: (params) => {
        const item = params[0]
        return `${item.axisValue}<br/>${t('17_transfer2')}: <b>${formatVal(item.data)}</b>`
      }
    },
    // ✅ 调整 grid.top，防止顶部文字被遮挡
    grid: { left: 18, right: 20, top: 60, bottom: 18 },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: xAxis,
      axisLine: { lineStyle: { color: '#ccc' } },
      axisLabel: { color: '#888' }
    },
    yAxis: {
      type: 'value',
      show: false,
      min: yMin,
      max: yMax,
      axisLine: { show: false },
      axisLabel: { show: false },
      axisTick: { show: false },
      splitLine: { show: false }
    },
    series: [
      {
        name: t('22_balanceTrend'),
        data: series,
        type: 'line',
        smooth: true,
        showSymbol: true,
        symbol: 'circle',
        symbolSize: 6,
        lineStyle: {
          width: 3,
          color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
            { offset: 0, color: '#00E6B8' },
            { offset: 0.5, color: '#17AC74' },
            { offset: 1, color: '#00C896' }
          ])
        },
        itemStyle: { color: '#17AC74', borderColor: '#fff' },
        label: {
          show: true,
          position: 'top',
          color: '#17AC74',
          fontSize: 11,
          formatter: (v) => formatVal(v.data)
        },
        areaStyle: {
          opacity: 0.4,
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(23,172,116,0.35)' },
            { offset: 1, color: 'rgba(23,172,116,0)' }
          ])
        },
        animationDuration: 1000
      }
    ]
  })
}





// 切换天数
function switchDays(days) {
  if (daysType.value !== days) {
    daysType.value = days
    fetchAllBalance()
  }
}

onMounted(() => {
  nextTick(() => {
    chartInstance = echarts.init(chartRef.value)
    fetchAllBalance()
  })
})

onBeforeUnmount(() => {
  if (chartInstance) chartInstance.dispose()
})

// ✅ 监听账户切换（真实 ↔ 模拟）时刷新 K 线数据
import { watch } from 'vue'
watch(
  () => userStore.isDemo,
  (newVal, oldVal) => {
    console.log('账户切换：', oldVal, '→', newVal)
    fetchAllBalance()
  }
)

</script>

<style lang="scss" scoped>
.chart-card {
  background: #f7f9fa;
  border-radius: 16px;
  max-width: 420px;
  margin: 0 auto;
}
.chart-container {
  box-shadow: 0 2px 8px rgba(31, 35, 41, 0.04);
  background: #fff;
  border-radius: 16px;
  padding: 20px 0;
}
.line-chart-container {
  position: relative;
  padding: 0 12px;
}
.chart-box {
  width: 100%;
  height: 240px;
}
.chart-loading,
.chart-empty {
  position: absolute;
  inset: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: rgba(255, 255, 255, 0.7);
  border-radius: 12px;
}
.chart-empty-img {
  width: 80px;
  height: 80px;
  opacity: 0.6;
}
.chart-empty-text {
  margin-top: 10px;
  font-size: 13px;
  color: #999;
}
.chart-btn-group {
  display: flex;
  justify-content: center;
  gap: 16px;
  margin: 24px 0 0 0;
}
.chart-btn {
  width: 120px;
  height: 35px;
  border-radius: 24px;
  border: 1px solid #e5e6eb;
  background: #fff;
  color: #222;
  font-size: 16px;
  font-weight: 500;
  transition: all 0.2s;
}
.chart-btn.active {
  background: #17AC74;
  color: #fff;
  border-color: #17AC74;
}
.account-card {
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 2px 8px 0 rgba(31, 35, 41, 0.04);
  padding: 32px 24px 24px 24px;
  max-width: 420px;
  margin: 0 auto 32px auto;
}
.account-title {
  font-size: 16px;
  font-weight: bold;
  color: #222;
  margin-bottom: 18px;
}
.account-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}
.account-item {
  display: flex;
  align-items: flex-start;
}
.account-main {
  flex: 1;
  display: flex;
  flex-direction: column;
}
.account-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.account-icon-bg {
  width: 28px;
  height: 28px;
  border-radius: 50%;
  background: #f7f9fa;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
}
.account-icon {
  width: 24px;
  height: 24px;
  object-fit: contain;
}
.account-name {
  flex: 1;
  font-size: 12px;
  color: #222;
}
.account-value {
  font-size: 12px;
  color: #222;
  min-width: 110px;
  text-align: right;
}
.account-percent {
  color: #bdbdbd;
  font-size: 10px;
}
.account-progress-bar-bg {
  width: 100%;
  height: 6px;
  background: #f2f3f5;
  border-radius: 3px;
  margin-top: 14px;
  margin-bottom: 12px;
}
.account-progress-bar {
  height: 100%;
  border-radius: 3px;
  transition: width 0.4s;
}
</style>
